package icu.xuyijie.springbootlearning2.chapter3.mybatis;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

/**
 * @author 徐一杰
 * @date 2025/02/25 13:57
 * @description
 */
@RestController
@RequestMapping("/mybatis")
@Tag(name = "Mybatis操作数据库相关的接口")
public class MybatisController {

    @Autowired
    private MyEntityMapper myEntityMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @GetMapping("/findOne")
    // 允许此方法跨域
    //@CrossOrigin
    @Operation(summary = "根据id查询一条数据", parameters = {
            @Parameter(name = "id", description = "要查询的主键")
    })
    public MyEntity findOne(Integer id, HttpSession session) {
        System.out.println(session.getId());
        MyEntity myEntity = myEntityMapper.getMyEntityById(id);
        System.out.println(myEntity);
        return myEntity;
    }

    @GetMapping("/findAll")
    public void findAll() {
        long start0 = System.currentTimeMillis();
        // 判断是否有缓存
        List<Object> aaaList = redisTemplate.opsForList().range("aaa", 0, -1);
        if (aaaList.size() > 0) {
            // 有的话，直接取缓存，并返回，下方查询MySQL的代码就不执行了
            System.out.println(aaaList);
            System.out.println("有缓存的查询时间：" + (System.currentTimeMillis() - start0) + "ms");
            return;
        }

        // 记录当前毫秒数
        long startTime = System.currentTimeMillis();

        List<MyEntity> list = myEntityMapper.findAll();
        System.out.println(list);

        // 计算中间代码消耗的时间
        long endTime = System.currentTimeMillis() - startTime;
        System.out.println("无缓存时查询耗时：" + endTime + "ms");

        // 把MySQL种查询到数据塞进缓存
        redisTemplate.opsForList().leftPushAll("aaa", list);
    }

    @GetMapping("/add")
    public void add() {
        MyEntity entity = new MyEntity();
        entity.setName("dfdaasassa");
        entity.setCreateTime(new Date());
        myEntityMapper.insert(entity);
    }

    @GetMapping("/update")
    public void update() {
        myEntityMapper.update("111111111111111", 1);
    }

    @GetMapping("/del")
    public void del() {
        myEntityMapper.delete(8);
    }

}
